// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    isEditMode: false,
    selectAll: false,
    totalPrice: '0.00',
    selectedCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("show");
    var value = wx.getStorageSync('token')
    var name = wx.getStorageSync('userid')
    
    if (!value || !name) {
      // 未登录状态
      this.setData({
        cartList: []
      });
      
      // 显示未登录提示框
      wx.showModal({
        title: '未登录',
        content: '您尚未登录，请先登录后查看购物车',
        confirmText: '去登录',
        cancelText: '取消',
        success: function(res) {
          if (res.confirm) {
            // 用户点击了登录按钮
            wx.navigateTo({
              url: '/pages/logs/logs',
            })
          }
        }
      });
      return;
    }
    
    var that = this;
    wx.request({
      url: 'http://47.94.6.186:3001/api/cart/list',
      method: "POST",
      header: {
        token: value
      },
      data: {
        userid: name
      },
      success: function(res) {
        console.log(res.data.data);
        // 为每个商品添加选中状态和数量属性
        var cartList = res.data.data;
        for (var i = 0; i < cartList.length; i++) {
          cartList[i].selected = false;
          cartList[i].quantity = cartList[i].quantity || 1;
        }
        
        that.setData({
          cartList: cartList
        });
        
        that.calculateTotal();
        console.log(that.data.cartList);
      }
    })
  },

  /**
   * 切换编辑模式
   */
  toggleEditMode: function() {
    this.setData({
      isEditMode: !this.data.isEditMode
    });
  },

  /**
   * 选择单个商品
   */
  selectItem: function(e) {
    var id = e.currentTarget.dataset.id;
    var cartList = this.data.cartList;
    var selectAll = true;
    
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].cartid === id) {
        cartList[i].selected = !cartList[i].selected;
      }
      if (!cartList[i].selected) {
        selectAll = false;
      }
    }
    
    this.setData({
      cartList: cartList,
      selectAll: selectAll
    });
    
    this.calculateTotal();
  },

  /**
   * 全选/取消全选
   */
  selectAll: function() {
    var selectAll = !this.data.selectAll;
    var cartList = this.data.cartList;
    
    for (var i = 0; i < cartList.length; i++) {
      cartList[i].selected = selectAll;
    }
    
    this.setData({
      selectAll: selectAll,
      cartList: cartList
    });
    
    this.calculateTotal();
  },

  /**
   * 增加商品数量
   */
  increaseQuantity: function(e) {
    var id = e.currentTarget.dataset.id;
    var cartList = this.data.cartList;
    var quantity = 0;
    
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].cartid === id) {
        cartList[i].quantity += 1;
        quantity = cartList[i].quantity;
        break;
      }
    }
    
    this.setData({
      cartList: cartList
    });
    
    this.calculateTotal();
    this.updateCartItemQuantity(id, quantity);
  },

  /**
   * 减少商品数量
   */
  decreaseQuantity: function(e) {
    var id = e.currentTarget.dataset.id;
    var cartList = this.data.cartList;
    var quantity = 0;
    
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].cartid === id && cartList[i].quantity > 1) {
        cartList[i].quantity -= 1;
        quantity = cartList[i].quantity;
        break;
      }
    }
    
    this.setData({
      cartList: cartList
    });
    
    this.calculateTotal();
    this.updateCartItemQuantity(id, quantity);
  },

  /**
   * 更新购物车商品数量
   */
  updateCartItemQuantity: function(cartId, quantity) {
    var value = wx.getStorageSync('token')
    var name = wx.getStorageSync('userid')
    
    wx.request({
      url: 'http://47.94.6.186:3001/api/cart/updatenum',
      method: "POST",
      header: {
        token: value
      },
      data: {
        userid: name,
        cartid: cartId,
        quantity: quantity
      },
      success: function(res) {
        console.log('更新数量成功', res.data);
      }
    });
  },

  /**
   * 删除购物车商品
   */
  deleteItem: function(e) {
    var id = e.currentTarget.dataset.id;
    var value = wx.getStorageSync('token')
    var name = wx.getStorageSync('userid')
    var that = this;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个商品吗？',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: 'http://47.94.6.186:3001/api/cart/remove',
            method: "POST",
            header: {
              token: value
            },
            data: {
              userid: name,
              cartid: id
            },
            success: function(res) {
              console.log('删除成功', res.data);
              // 更新本地数据
              var cartList = [];
              for (var i = 0; i < that.data.cartList.length; i++) {
                if (that.data.cartList[i].cartid !== id) {
                  cartList.push(that.data.cartList[i]);
                }
              }
              
              that.setData({
                cartList: cartList
              });
              that.calculateTotal();
              
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 计算总价和选中商品数量
   */
  calculateTotal: function() {
    var total = 0;
    var count = 0;
    var cartList = this.data.cartList;
    
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].selected) {
        total += cartList[i].originprice * cartList[i].quantity;
        count += cartList[i].quantity;
      }
    }
    
    this.setData({
      totalPrice: total.toFixed(2),
      selectedCount: count
    });
  },

  /**
   * 结算
   */
  checkout: function() {
    var selectedItems = [];
    var cartList = this.data.cartList;
    
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].selected) {
        selectedItems.push(cartList[i]);
      }
    }
    
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
    
    // 这里可以跳转到结算页面
    wx.showToast({
      title: '前往结算',
      icon: 'success'
    });
  },

  /**
   * 去购物
   */
  goShopping: function() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log('hide');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})